package com.example.springaop.xw;

import com.alibaba.fastjson.JSON;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DemoTest {

    public static Map<String, Integer> list = new HashMap<>();
    public static Map<String, String> resultMap = new HashMap<>();

    private static final String CHARSET_UTF8 = "UTF-8";

    public static volatile List<String[]> rcontent = new ArrayList<>();

    private static final String SERVICE_URL = "https://api.iflyrec.com";
    private static String accessKeyId = "pr9Sw8eMQa";
    private static String accessKeySecret = "5rQ4Lr0z1D8Ju1T3s1KBWPU5O1lW9Hce";

    public static void main(String[] args) throws Exception {
        readCSV("/data/6000mp3_1.csv");

        ExecutorService service = Executors.newFixedThreadPool(10);
        int index = 0;
        for (Map.Entry<String, Integer> vo : list.entrySet()) {
            index++;
            if (!vo.getKey().contains("https")) {
                continue;
            }

            /*if (index > 1) {
                break;
            }*/

//			run1(vo);

            MyRunnableTest myRunnableTest = new MyRunnableTest(vo,"name"+index);
			/*Thread thread=new Thread(myRunnableTest);
			thread.start();*/
            service.execute(myRunnableTest);
        }

        service.shutdown();
        try {
            while (true) {
                if (service.isTerminated()) {
                    System.out.println("所有的子线程都结束了！");
                    break;
                } else {
                    System.out.println("执行中！");
                }
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void run1(Map.Entry<String, Integer> vo) {
        try {
            System.out.println(Thread.currentThread().getName());
            String remoteFilePath = vo.getKey();
            URL url = new URL(remoteFilePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-xbap,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");
            conn.setRequestProperty("Accept-Language", "zh-CN");
            conn.setRequestProperty("Charset", "UTF-8");
            InputStream is = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int hasRead = 0;
            while ((hasRead = is.read(buffer)) != -1) {
                System.out.println("我执行了");
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void step01_upload() throws Exception {

        readCSVOrder("/Users/wenba/result.csv");
        readCSVOrder("/Users/wenba/resultd.csv");
        readCSV("/Users/wenba/6000mp3.csv");
        ExecutorService service = Executors.newFixedThreadPool(10);
        int i = 0, k = 0;
        try {
            for (Map.Entry<String, Integer> vo : list.entrySet()) {
                if (!vo.getKey().contains("https")) {
                    i++;
                    continue;
                }
                if (resultMap.get(vo.getKey()) == null) {
                    k++;
                    if (k == 1) {
                        service.execute(new MyRunnableTest(vo,String.valueOf(i)));
                    }
                }
            }
        } catch (Exception e) {
        }
        service.shutdown();
    }

    public static byte[] getFileStream(String url) {
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取数据
            byte[] bytes = readInputStream(inStream);//得到的二进制数据
            return bytes;
        } catch (Exception e) {
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 生成CSV文件
     */
    public boolean createCSV(List<String[]> strs) throws Exception {
        String filePath = "/Users/wenba/resultnew.csv";
        char separator = ',';
        boolean isSuccess = false;
        CsvWriter writer = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath, true);
            //如果生产文件乱码，windows下用gbk，linux用UTF-8
            writer = new CsvWriter(out, separator, Charset.forName("GBK"));
            for (String[] str : strs) {
                writer.writeRecord(str);
            }
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return isSuccess;
    }

    public static boolean createCSV1(String[] strs) throws Exception {
        String filePath = "/Users/wenba/result1.csv";

        char separator = ',';
        boolean isSuccess = false;
        CsvWriter writer = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath, true);
            //如果生产文件乱码，windows下用gbk，linux用UTF-8
            writer = new CsvWriter(out, separator, Charset.forName("UTF-8"));
            writer.writeRecord(strs);
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return isSuccess;
    }


    /**
     * 读取CSV文件
     *
     * @param filePath:全路径名
     */
    public static List<String[]> readCSV(String filePath) throws Exception {
        CsvReader reader = null;
        char separator = ',';
        List<String[]> dataList = new ArrayList<String[]>();
        try {
            //如果生产文件乱码，windows下用gbk，linux用UTF-8
            reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));

            // 读取表头
            reader.readHeaders();
            String[] headArray = reader.getHeaders();//获取标题
            System.out.println(headArray[0] + headArray[1] + headArray[2]);

            // 逐条读取记录，直至读完
            while (reader.readRecord()) {
//				TextInfo info = new TextInfo();
//				info.setDuration(Integer.parseInt(reader.get("speech_len")));
//				info.setPath(reader.get("name"));

                list.put(reader.get("name"), Integer.parseInt(reader.get("speech_len")));
//				// 读一整行
//				System.out.println(reader.getRawRecord());
//				// 读这行的第一列
//				System.out.println(reader.get("name"));
//				// 读这行的第二列
//				System.out.println(reader.get(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

        return dataList;
    }


    public static List<String[]> readCSVOrder(String filePath) throws Exception {
        CsvReader reader = null;
        char separator = ',';
        List<String[]> dataList = new ArrayList<String[]>();
        try {
            //如果生产文件乱码，windows下用gbk，linux用UTF-8
            reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));

            // 读取表头
            reader.readHeaders();
            String[] headArray = reader.getHeaders();//获取标题
            System.out.println(headArray[0] + headArray[1] + headArray[2]);

            // 逐条读取记录，直至读完
            while (reader.readRecord()) {
                resultMap.put(reader.get(0), reader.get(2));
//				// 读一整行
//				System.out.println(reader.getRawRecord());
//				// 读这行的第一列
//				System.out.println(reader.get("name"));
//				// 读这行的第二列
//				System.out.println(reader.get(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

        return dataList;
    }


}
